using System.Collections;
using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Iterate V2")]
	[Category("Decorators")]
	[Description("Iterate a list and execute the child node for each element in the list. Keeps iterating until the Termination Condition is met or the whole list is iterated and return the child node status")]
	[Icon("List")]
	public class BTIteratorV2 : BTDecorator
	{
		public enum TerminationConditions
		{
			FirstSuccess = 0,
			FirstFailure = 1,
			None = 2
		}

		[BlackboardOnly]
		[VariableType(typeof(IList))]
		public BBVar list;

		[BlackboardOnly]
		public BBVar current;

		public BBInt maxIteration;

		public TerminationConditions terminationCondition = TerminationConditions.None;

		public bool resetIndex = true;

		private int currentIndex;

		private IList iList
		{
			get
			{
				return (list == null || list.value == null) ? null : (list.value as IList);
			}
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			if (!base.decoratedConnection)
			{
				return Status.Resting;
			}
			if (iList == null || iList.Count == 0)
			{
				return Status.Failure;
			}
			current.value = iList[currentIndex];
			base.status = base.decoratedConnection.Execute(agent, blackboard);
			if (base.status == Status.Success && terminationCondition == TerminationConditions.FirstSuccess)
			{
				return Status.Success;
			}
			if (base.status == Status.Failure && terminationCondition == TerminationConditions.FirstFailure)
			{
				return Status.Failure;
			}
			if (base.status != Status.Running)
			{
				if (currentIndex == iList.Count - 1 || currentIndex == maxIteration.value - 1)
				{
					return base.status;
				}
				base.decoratedConnection.ResetConnection();
				currentIndex++;
				return Status.Running;
			}
			return base.status;
		}

		protected override void OnReset()
		{
			if (resetIndex || currentIndex == iList.Count - 1 || currentIndex == maxIteration.value - 1)
			{
				currentIndex = 0;
			}
		}
	}
}
